﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using BeetleX.Http.Clients;
using DEEBCG.ExternalLib.CompanyAPI;
using DEEBCG.ExternalLib.CompanyAPI.Model;

namespace CompanyAPITestProject
{
    /// <summary>
    /// Token保存管理类
    /// </summary>
    internal class TokenManage
    {
        public static TokenInfo Token = null;

        public static async Task<TokenInfo> GetTokenAsync()
        {
            if (Token == null || Token.ExpireTime >= DateTime.Now)
            {
                AppInfo app = new AppInfo(Settings.AppID, Settings.Secret, Settings.AppName);
                //重新获取token
                HttpCluster httpCluster = new HttpCluster();
                httpCluster.DefaultNode.Add(Settings.BaseUrl);
                var token = httpCluster.Create<IToken>();

                var result = await token.GetToken(app.AppID, app.GetPassword(), app.NoiseStr, app.Timestamp);
                if (result != null && result.Status == 200 && result.Data != null)
                {
                    Token = result.Data;
                    return result.Data;
                }
                else
                {
                    throw new ArgumentNullException("Token信息丢失。");
                }
            }
            else
            {
                return Token;
            }
        }
    }
}
